<template>
  <section>
    <div class="page-wrapper">
      <van-sticky>
        <PageHeader title="注册" />
      </van-sticky>

      <div class="flex flex-col pd20">
        <div class="mt10 flex flex-center flex-row" v-if="wxUserInfo">
          <img :src="wxUserInfo.headimgurl" class="headimgurl" />
        </div>

        <div class="mt5 mb20 flex flex-center flex-row font-common" v-if="wxUserInfo">
          {{wxUserInfo.nickname}}
        </div>

        <van-cell-group>
          <van-field v-model="user.mobile" required center clearable type="tel" label="手机号" placeholder="请输入手机号" />

          <van-field
            v-model="user.img_captcha"
            required
            center
            clearable
            label="图形码"
            placeholder="请输入图形码">
            <template #button v-if="captchaImage">
              <img :src="captchaImage" height="35" width="100" @click="getCaptcha" />
            </template>
          </van-field>

          <van-field
            v-model="user.sms_captcha"
            required
            center
            clearable
            label="验证码"
            placeholder="请输入短信验证码">
            <template #button>
              <van-button :disabled="sending" size="small" type="primary" @click="sendSms">{{smsLabel}}</van-button>
            </template>
          </van-field>
        </van-cell-group>

        <div class="flex flex-row flex-centerV flex-left mt10 color-gray font-common">
          <van-checkbox v-model="checked">我同意用户协议</van-checkbox>
          <router-link :to="{name: 'TermsConditions'}" class="blue mr10 ml10">&lt;&lt;用户协议&gt;&gt;</router-link>
          <router-link :to="{name: 'PrivacyPolicy'}" class="blue">&lt;&lt;隐私政策&gt;&gt;</router-link>
        </div>

        <div class="bg-color-white text-center btn-submit mt15">
          <van-button size="large" type="primary" round :loading="submitting" loading-text="注册中" @click="register">注册</van-button>
        </div>

        <div class="flex flex-row flex-center mt15 color-gray font-common"><span @click="$router.replace({name: 'UserLogin'})">已有账号？立即登录</span></div>
      </div>
    </div>

  </section>
</template>

<script>
  import util from '../../assets/js/util';
  import PageHeader from "../componets/PageHeader";
  import {
    captchaEntryUri,
    wxUserInfoByCodeUri,
    registerByWxUserInfoUri,
    smsCaptchaSendUri,
    userLoginUri
  } from "../../common/api";
  import Vue from 'vue';
  import {Sticky, Popup, RadioGroup, Radio, CellGroup, Field, Toast, Checkbox, Button} from "vant";
  Vue.use(Sticky).use(Popup).use(RadioGroup).use(Radio).use(CellGroup).use(Field).use(Checkbox).use(Button);

  export default {
    components: {
      PageHeader
    },
    data() {
      return {
        wxUserInfo: null,
        user: {id: 0, mobile: '', img_captcha: '', sms_captcha: ''},
        submitting: false,
        smsLabel: '发送验证码',
        sending: false,
        sessionId: '',
        captchaImage: '',
        checked: false
      }
    },
    methods: {
      getCaptcha() {
        const that = this;
        const url = captchaEntryUri;
        this.$http.get(url).then(response => {
          let {code, msg, data} = response.body
          if (code != 0) {
            Toast.fail(msg);
          } else {
            that.sessionId = data.session_id;
            that.captchaImage = data.captcha;
          }
        }, response => {
          // error callback
        })
      },
      sendSms() {
        if(this.sending) {
          return;
        }
        if(this.user.mobile.length == 0 || this.user.img_captcha.length == 0) {
          Toast('手机号和图形验证码不能为空');
          return
        }
        const that = this;
        const url = smsCaptchaSendUri + '?mobile=' + this.user.mobile + '&img_captcha=' + this.user.img_captcha + '&session_id=' + this.sessionId + '&type=register';
        this.$http.get(url).then(response => {
          let {code, msg, data} = response.body
          if (code != 0) {
            that.getCaptcha();
            Toast.fail(msg);
          } else {
            that.sending = true;
            that.interval = 60;
            that.intv = setInterval(()=>{
              if(that.interval <= 0) {
                that.smsLabel = '发送验证码';
                that.sending = false;
                clearInterval(that.intv);
              } else {
                that.smsLabel = '剩余('+that.interval+')秒';
                that.interval--;
              }
            }, 1000);
            that.getCaptcha();
          }
        }, response => {
          // error callback
        })
      },
      register() {
        if(!this.checked) {
          Toast('必须同意用户协议才可注册');
          return;
        }
        if(this.wxUserInfo == null) {
          Toast('获取微信昵称失败');
          return
        }
        if(this.user.mobile.length == 0 || this.user.sms_captcha.length == 0) {
          Toast('手机号和验证码不能为空');
          return
        }
        const fromuid = localStorage.getItem('fromuid') ? localStorage.getItem('fromuid') : 0;
        const that = this;
        let formData = this.wxUserInfo;
        formData['mobile'] = this.user.mobile;
        formData['sms_captcha'] = this.user.sms_captcha;
        formData['fromuid'] = fromuid;

        that.$http.post(registerByWxUserInfoUri, formData, {emulateJSON: true}).then(response => {
          let {msg, code, data} = response.body
          if (code != 0) {
            Toast.fail(msg)
          } else {
            Toast.success('注册成功');

            that.EventBus.$emit('OnUserLogined', {user: data.user, member: data.member, method: 'register'});

            const referrer = localStorage.getItem('referrer');
            if(referrer) {
              that.$router.replace(referrer);
            } else {
              that.$router.replace({name: 'MyIndex'});
            }
          }
        }, response => {
          Toast.fail('发生错误')
        })
      },
      getWxUserInfo(code) {
        const that = this;
        const url = wxUserInfoByCodeUri + '?code=' + code;
        this.$http.get(url).then(response => {
          let {code, msg, data} = response.body
          if (code != 0) {
            Toast.fail(msg);
          } else {
            if(data.wx_user_info == null) {
              Toast.fail('获取微信昵称失败');
            } else {
              console.log(data);
              that.wxUserInfo = data.wx_user_info;
            }
          }
        }, response => {
          // error callback
        })
      }
    },
    mounted: function () {
      // const hash = window.location.hash;
      // if(hash.indexOf('?') != -1) {
      //   const query = hash.split('?')[1];
      //   const code = util.getVariableByQuery(query, 'code');
      //   console.log('code:' + code);
      // } else {  // 跳转到微信获取code
      //   const href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='+WECHAT_APP_API+'&redirect_uri='+encodeURIComponent(window.location.href)+'&response_type=code&scope=snsapi_userinfo&state=#wechat_redirect';
      //   window.location.href = href;
      // }

      this.getCaptcha();

      const code = util.getQueryVariable('code');
      if(code) {
        //防止页面后退
        history.pushState(null, null, document.URL);
        window.addEventListener('popstate', function () {
          history.pushState(null, null, document.URL);
        });
        this.getWxUserInfo(code);
      } else {
        if(isWxServiceEnable) {
          const href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='+WECHAT_APP_ID+'&redirect_uri='+encodeURIComponent(window.location.href)+'&response_type=code&scope=snsapi_userinfo&state=#wechat_redirect';
          window.location.href = href;
        }
      }
    }
  }
</script>

<style scoped>
  .page-wrapper {
    background: #FFFFFF;
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
  }
  .headimgurl {
    height: 60px;
    width: 60px;
    border-radius: 30px;
  }
</style>
